package com.chengyu.core.service.ty.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;
import com.chengyu.core.domain.enums.MemberNewsEnums;
import com.chengyu.core.domain.enums.MemberRemindEnums;
import com.chengyu.core.domain.enums.OrderEnums;
import com.chengyu.core.domain.form.MemberNewsForm;
import com.chengyu.core.domain.form.OrderRefundSearchForm;
import com.chengyu.core.domain.form.TyOrderRefundForm;
import com.chengyu.core.domain.form.TyOrderRefundSearchForm;
import com.chengyu.core.domain.result.ChatNotice;
import com.chengyu.core.domain.result.CustomerConstant;
import com.chengyu.core.domain.result.TyOrderRefundResult;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.mapper.TyOrderMapper;
import com.chengyu.core.mapper.TyOrderRefundLogMapper;
import com.chengyu.core.mapper.TyOrderRefundMapper;
import com.chengyu.core.model.*;
import com.chengyu.core.service.config.ConfigOrderService;
import com.chengyu.core.service.im.ChatService;
import com.chengyu.core.service.member.MemberNewsService;
import com.chengyu.core.service.member.MemberService;
import com.chengyu.core.service.pay.TyPayService;
import com.chengyu.core.service.schedule.RedisDelayQueueEnum;
import com.chengyu.core.service.schedule.RedisDelayQueueUtil;
import com.chengyu.core.service.shop.ShopService;
import com.chengyu.core.service.ty.TyOrderRefundService;
import com.chengyu.core.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author LeGreen
 * @title 订单售后
 * @date 2022/4/29
 */
@Service
public class TyOrderRefundServiceImpl implements TyOrderRefundService {

    @Autowired
    private TyOrderRefundMapper orderRefundMapper;
    @Autowired
    private TyOrderRefundLogMapper orderRefundLogMapper;
    @Autowired
    private TyOrderMapper orderMapper;
    //	@Autowired
//	private ShopConfigService shopConfigService;
//	@Autowired
//	private ConfigOrderService configOrderService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberNewsService memberNewsService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private TyPayService payService;
    @Autowired
    private ChatService chatService;
    @Autowired
    private RedisDelayQueueUtil redisDelayQueueUtil;

    @Autowired
    private ConfigOrderService configOrderService;


    @Override
    public List<TyOrderRefund> getRefundList(TyOrderRefundSearchForm form, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        TyOrderRefundExample example = new TyOrderRefundExample();
        if (StringUtils.isNotBlank(form.getSort())) {
            example.setOrderByClause(form.getSort());
        } else {
            example.setOrderByClause("add_time desc");
        }
        TyOrderRefundExample.Criteria criteria = example.createCriteria();
        if (form.getMemberId() != null) {
            criteria.andMemberIdEqualTo(form.getMemberId());
        }
        if (StringUtils.isNotBlank(form.getMemberName())) {
            criteria.andMemberNameLike("%" + form.getMemberName() + "%");
        }
        if (form.getShopId() != null) {
            criteria.andShopIdEqualTo(form.getShopId());
        }
        if (StringUtils.isNotBlank(form.getRefdundNo())) {
            criteria.andRefundNoLike("%" + form.getRefdundNo() + "%");
        }
        if (form.getStatus() != null) {
            criteria.andStatusEqualTo(form.getStatus());
        }
        if (form.getDateFrom() != null && form.getDateTo() != null) {
            criteria.andAddTimeBetween(form.getDateFrom(), form.getDateTo());
        }
        if (CollectionUtil.isNotEmpty(form.getStatusList())) {
            criteria.andStatusIn(form.getStatusList());
        }
        return orderRefundMapper.selectByExample(example);
    }

    @Override
    public TyOrderRefundResult getOrderRefund(Integer refundId) {
        TyOrderRefundResult result = new TyOrderRefundResult();
        result.setRefund(orderRefundMapper.selectByPrimaryKey(refundId));

        TyOrderRefundLogExample example = new TyOrderRefundLogExample();
        example.setOrderByClause("add_time desc");
        example.createCriteria().andRefundIdEqualTo(refundId);
        result.setRefundLogList(orderRefundLogMapper.selectByExample(example));
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void applyRefund(UmsMember member, TyOrderRefundForm form) throws ServiceException {
        TyOrder order = orderMapper.selectByPrimaryKey(form.getOrderId());
        TyOrderRefund refund = new TyOrderRefund();
        refund.setRefundNo("R" + StringUtils.genOrderNo(member.getId()));
        refund.setOrderId(form.getOrderId());
        refund.setMemberId(member.getId());
        refund.setMemberName(member.getCode());
        refund.setHeadImg(member.getHeadImg());
        refund.setRefundInd(form.getRefundInd());
        refund.setBuyTime(order.getAddTime());
        refund.setOriginalAmount(order.getPayPrice());
        refund.setShopId(order.getShopId());
        refund.setShopName(order.getShopName());
        refund.setRefundAmount(form.getRefundAmount());
        refund.setReason(form.getReason());
        refund.setImg(form.getImg());
        refund.setStatus(OrderEnums.RefundDetailStatus.APPLY.getValue());
        refund.setPayMethod(order.getPayMethod());
        refund.setRefundTime(DateUtil.date());
        refund.setAddTime(DateUtil.date());
        refund.setUpdTime(refund.getAddTime());
        //超过该时间未处理,自动同意
        ConfigOrder config = configOrderService.getConfigOrder();
        refund.setAutoAgreeTime(DateUtil.offsetDay(refund.getAddTime(), config.getAutoAgreeRefundDay()));
        orderRefundMapper.insertSelective(refund);

        //自动同意定时器

        System.out.println("redisDelayQueueUtil.addDelayQueue:"+refund.getAutoAgreeTime());

        redisDelayQueueUtil.addDelayQueue(refund.getRefundNo(), refund.getAutoAgreeTime(), RedisDelayQueueEnum.REFUND_AUTO_AGREE_JOB.getCode());
//		taskTriggerService.addTrigger(RefundAutoAgreeJob.class, refund.getAutoAgreeTime(), refund.getRefundNo());

        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(order.getId());
        updateOrder.setRefundStatus(OrderEnums.RefundStatus.REFUNDING.getValue());
        orderMapper.updateByPrimaryKeySelective(updateOrder);

        //记录
        TyOrderRefundLog log = new TyOrderRefundLog();
        log.setRefundId(refund.getId());
        log.setRefundNo(refund.getRefundNo());
        log.setOperatorId(member.getId());
        log.setOperatorName(member.getCode());
        log.setHeadImg(member.getHeadImg());
        StringBuilder content = new StringBuilder();
        content.append("买家申请退款(").append(refund.getRefundInd() == 1 ? "仅退款" : "退货退款").append(")");
        content.append(",退款原因:").append(refund.getReason());
        content.append(",退款金额:").append(refund.getRefundAmount());
        log.setContent(content.toString());
        log.setAddTime(DateUtil.date());
        log.setUpdTime(log.getAddTime());
        orderRefundLogMapper.insert(log);

        ChatNotice notice = new ChatNotice();
        notice.setTitle("重要! 有用户申请售后,请及时处理~");
        notice.setContent(JSONUtil.toJsonStr(refund));
        notice.setType(MemberRemindEnums.MemberRemindTypes.WAIT_VERIFY_REFUND.getType());
//        UmsShop shop = shopService.getShopById(order.getShopId());

        chatService.sendNoticeMsg(order.getMerMemberId(), JSONUtil.toJsonStr(notice));
//		memberRemindService.addShopRemind(order.getShopId(), MemberRemindEnums.MemberRemindTypes.WAIT_VERIFY_REFUND, "重要! 有用户申请售后,请及时处理~");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void agreeRefund(UmsShop shop, Integer refundId) throws ServiceException {
        TyOrderRefund refund = this.getRefundByShop(shop, refundId);
        if (refund.getStatus() != OrderEnums.RefundDetailStatus.APPLY.getValue()) {
            throw new ServiceException("order.refund.agree.error");
        }
        //同意退款
        this.agreeRefundOrSalesReturn(refund);
        //记录
        TyOrderRefundLog log = new TyOrderRefundLog();
        log.setRefundId(refund.getId());
        log.setRefundNo(refund.getRefundNo());
        log.setOperatorId(shop.getId());
        log.setOperatorName(shop.getName());
        log.setHeadImg(shop.getLogo());
        StringBuilder content = new StringBuilder();
        content.append("卖家同意退款申请(").append(refund.getRefundInd() == 1 ? "仅退款" : "退货退款").append(")");
        log.setContent(content.toString());
        log.setAddTime(DateUtil.date());
        log.setUpdTime(log.getAddTime());
        orderRefundLogMapper.insert(log);
    }

    /**
     * 退款成功更新原订单信息
     *
     * @param refund
     * @author LeGreen
     * @date 2022/5/6
     */
    private void refundSusForUpdateOrder(TyOrderRefund refund) {
        TyOrder order = orderMapper.selectByPrimaryKey(refund.getOrderId());
        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(order.getId());
        updateOrder.setRefundAmount(NumberUtil.add(order.getRefundAmount(), refund.getRefundAmount()));
        updateOrder.setRefundStatus(3);
        if (updateOrder.getRefundStatus() == 3) {
            updateOrder.setStatus(OrderEnums.OrderStatus.CANCEL.getValue());
        }
        orderMapper.updateByPrimaryKeySelective(updateOrder);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void refuseRefund(UmsShop shop, Integer refundId, String reason) throws ServiceException {
        TyOrderRefund refund = this.getRefundByShop(shop, refundId);
        if (refund.getStatus() != OrderEnums.RefundDetailStatus.APPLY.getValue()) {
            throw new ServiceException("order.refund.refuse.error");
        }
        TyOrderRefund updateRefund = new TyOrderRefund();
        updateRefund.setId(refund.getId());
        updateRefund.setStatus(OrderEnums.RefundDetailStatus.SALES_REFUSE.getValue());
        orderRefundMapper.updateByPrimaryKeySelective(updateRefund);

        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(refund.getOrderId());
        updateOrder.setRefundStatus(OrderEnums.RefundStatus.REFUND_FAILED.getValue());
        orderMapper.updateByPrimaryKeySelective(updateOrder);

        //记录
        TyOrderRefundLog log = new TyOrderRefundLog();
        log.setRefundId(refund.getId());
        log.setRefundNo(refund.getRefundNo());
        log.setOperatorId(shop.getId());
        log.setOperatorName(shop.getName());
        log.setHeadImg(shop.getLogo());
        StringBuilder content = new StringBuilder();
        content.append("卖家拒绝退款申请(").append(refund.getRefundInd() == 1 ? "仅退款" : "退货退款").append(")");
        content.append(",拒绝原因:" + reason);
        log.setContent(content.toString());
        log.setAddTime(DateUtil.date());
        log.setUpdTime(log.getAddTime());
        orderRefundLogMapper.insert(log);

        //拒绝售后消息
        UmsMember member = memberService.getMemberById(refund.getMemberId());
        MemberNewsForm newsForm = new MemberNewsForm(MemberNewsEnums.MemberNewsTypes.NEWS_REFUSE_REFUND);
        newsForm.setShop(shopService.getShopById(refund.getShopId()));
        newsForm.initTurnParams("refundId", refund.getId().toString());
        memberNewsService.addMemberNews(member, newsForm);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void applyCustomerServiceIn(UmsMember member, Integer refundId) throws ServiceException {
        TyOrderRefund refund = this.getRefundByMember(member, refundId);
        if (refund.getStatus() != OrderEnums.RefundDetailStatus.SALES_REFUSE.getValue()) {
            throw new ServiceException("order.refund.customer.error");
        }
        TyOrderRefund updateRefund = new TyOrderRefund();
        updateRefund.setId(refund.getId());
        updateRefund.setStatus(OrderEnums.RefundDetailStatus.SERVICE_IN.getValue());
        orderRefundMapper.updateByPrimaryKeySelective(updateRefund);

        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(refund.getOrderId());
        updateOrder.setRefundStatus(OrderEnums.RefundStatus.REFUNDING.getValue());
        orderMapper.updateByPrimaryKeySelective(updateOrder);

        //记录
        TyOrderRefundLog log = new TyOrderRefundLog();
        log.setRefundId(refund.getId());
        log.setRefundNo(refund.getRefundNo());
        log.setOperatorId(member.getId());
        log.setOperatorName(member.getCode());
        log.setHeadImg(member.getHeadImg());
        log.setContent("买家申请客服介入");
        log.setAddTime(DateUtil.date());
        log.setUpdTime(log.getAddTime());
        orderRefundLogMapper.insert(log);

        ChatNotice notice = new ChatNotice();
        notice.setTitle("重要! 买家申请客服介入, 请及时处理~");
        notice.setContent(JSONUtil.toJsonStr(refund));
        notice.setType(MemberRemindEnums.AdminRemindTypes.WAIT_VERIFY_COMPLAINT.getType());
        chatService.sendNoticeMsg(CustomerConstant.ADMIN_MEMBER_ID, JSONUtil.toJsonStr(notice));
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void agreeRefundByCustomer(SysAdmin admin, Integer refundId) throws ServiceException {
        TyOrderRefund refund = orderRefundMapper.selectByPrimaryKey(refundId);
        if (refund.getStatus() != OrderEnums.RefundDetailStatus.SERVICE_IN.getValue()) {
            throw new ServiceException("order.refund.customer.join");
        }
        //同意退款
        this.agreeRefundOrSalesReturn(refund);
        //记录
        TyOrderRefundLog log = new TyOrderRefundLog();
        log.setRefundId(refund.getId());
        log.setRefundNo(refund.getRefundNo());
        log.setOperatorId(admin.getId());
        log.setOperatorName(admin.getName());
        log.setHeadImg(admin.getHeadImg());
        log.setContent("系统客服同意退款");
        log.setAddTime(DateUtil.date());
        log.setUpdTime(log.getAddTime());
        orderRefundLogMapper.insert(log);
    }

    /**
     * 同意退款退货
     *
     * @param refund
     * @throws ServiceException 业务异常
     * @author LeGreen
     * @date 2022/5/6
     */
    private void agreeRefundOrSalesReturn(TyOrderRefund refund) throws ServiceException {
        //仅退款，直接原路退款到账户
        payService.refund(refund.getRefundNo());

        //同意售后消息
        UmsMember member = memberService.getMemberById(refund.getMemberId());
        MemberNewsForm newsForm = new MemberNewsForm(MemberNewsEnums.MemberNewsTypes.NEWS_AGREE_REFUND);
        newsForm.setShop(shopService.getShopById(refund.getShopId()));
        newsForm.initTurnParams("refundId", refund.getId().toString());

        memberNewsService.addMemberNews(member, newsForm);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void refuseRefundByCustomer(SysAdmin admin, Integer refundId, String reason) throws ServiceException {
        TyOrderRefund refund = orderRefundMapper.selectByPrimaryKey(refundId);
        if (refund.getStatus() != OrderEnums.RefundDetailStatus.SERVICE_IN.getValue()) {
            throw new ServiceException("order.refund.customer.join");
        }
        TyOrderRefund updateRefund = new TyOrderRefund();
        updateRefund.setId(refund.getId());
        updateRefund.setStatus(OrderEnums.RefundDetailStatus.CLOSED.getValue());
        orderRefundMapper.updateByPrimaryKeySelective(updateRefund);


        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(refund.getOrderId());
        updateOrder.setRefundStatus(OrderEnums.RefundStatus.REFUND_FAILED.getValue());
        orderMapper.updateByPrimaryKeySelective(updateOrder);

        //记录
        TyOrderRefundLog log = new TyOrderRefundLog();
        log.setRefundId(refund.getId());
        log.setRefundNo(refund.getRefundNo());
        log.setOperatorId(admin.getId());
        log.setOperatorName(admin.getName());
        log.setHeadImg(admin.getHeadImg());
        log.setContent("客服拒绝退款:" + reason);
        log.setAddTime(DateUtil.date());
        log.setUpdTime(log.getAddTime());
        orderRefundLogMapper.insert(log);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void salesReturnByMember(UmsMember member, Integer refundId, String deliveryType, String deliveryNo) throws ServiceException {
        TyOrderRefund refund = this.getRefundByMember(member, refundId);
        if (refund.getStatus() != OrderEnums.RefundDetailStatus.WAIT_BUYER_RETURN.getValue()) {
            throw new ServiceException("order.refund.wait.delivery");
        }
        TyOrderRefund updateRefund = new TyOrderRefund();
        updateRefund.setId(refund.getId());
        updateRefund.setStatus(OrderEnums.RefundDetailStatus.BUYER_RETURNED.getValue());

        //超过该时间未收货,自动收货
//        ConfigOrder orderConfig = configOrderService.getConfigOrder();
//        updateRefund.setSellerConfirmTime(DateUtil.offsetDay(DateUtil.date(), orderConfig.getSellerReceiveDay()));
//        orderRefundMapper.updateByPrimaryKeySelective(updateRefund);

        //自动同意定时器
        redisDelayQueueUtil.addDelayQueue(refund.getRefundNo(), updateRefund.getSellerConfirmTime(), RedisDelayQueueEnum.REFUND_AUTO_CONFIRM_JOB.getCode());
//		taskTriggerService.addTrigger(RefundAutoConfirmJob.class, updateRefund.getSellerConfirmTime(), refund.getRefundNo());

        //记录
        TyOrderRefundLog log = new TyOrderRefundLog();
        log.setRefundId(refund.getId());
        log.setRefundNo(refund.getRefundNo());
        log.setOperatorId(member.getId());
        log.setOperatorName(member.getCode());
        log.setHeadImg(member.getHeadImg());
        log.setContent("买家已退货");
        log.setAddTime(DateUtil.date());
        log.setUpdTime(log.getAddTime());
        orderRefundLogMapper.insert(log);

        ChatNotice notice = new ChatNotice();
        notice.setTitle("重要! 买家已退货,请及时确认~");
        notice.setContent(JSONUtil.toJsonStr(refund));
        notice.setType(MemberRemindEnums.MemberRemindTypes.WAIT_CONFIRM_RECEIVE.getType());
        UmsShop shop = shopService.getShopById(refund.getShopId());
        chatService.sendNoticeMsg(shop.getMemberId(), JSONUtil.toJsonStr(notice));
//		memberRemindService.addShopRemind(refund.getShopId(), MemberRemindEnums.MemberRemindTypes.WAIT_CONFIRM_RECEIVE, "重要! 买家已退货,请及时确认~");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void confirmReceiveByShop(UmsShop shop, Integer refundId) throws ServiceException {
        TyOrderRefund refund = this.getRefundByShop(shop, refundId);
        if (refund.getStatus() != OrderEnums.RefundDetailStatus.BUYER_RETURNED.getValue()) {
            throw new ServiceException("order.refund.wait.receive");
        }
        TyOrderRefund updateRefund = new TyOrderRefund();
        updateRefund.setId(refund.getId());
        updateRefund.setStatus(OrderEnums.RefundDetailStatus.REFUND_SUS.getValue());
        orderRefundMapper.updateByPrimaryKeySelective(updateRefund);

        this.refundSusForUpdateOrder(refund);

        //记录
        TyOrderRefundLog log = new TyOrderRefundLog();
        log.setRefundId(refund.getId());
        log.setRefundNo(refund.getRefundNo());
        log.setOperatorId(shop.getId());
        log.setOperatorName(shop.getName());
        log.setHeadImg(shop.getLogo());
        log.setContent("卖家已收货,退款成功");
        log.setAddTime(DateUtil.date());
        log.setUpdTime(log.getAddTime());
        orderRefundLogMapper.insert(log);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void autoAgreeRefund(String refundNo) throws ServiceException {
        TyOrderRefund refund = this.getRefundByRefundNo(refundNo);
        if (refund != null && refund.getStatus() == OrderEnums.RefundDetailStatus.APPLY.getValue()) {
            //同意退款
            this.agreeRefundOrSalesReturn(refund);
            //记录
            TyOrderRefundLog log = new TyOrderRefundLog();
            log.setRefundId(refund.getId());
            log.setRefundNo(refund.getRefundNo());
            log.setOperatorId(refund.getShopId());
            log.setOperatorName(refund.getShopName());
            log.setContent("商家超时未处理,自动同意退款");
            log.setAddTime(DateUtil.date());
            log.setUpdTime(log.getAddTime());
            orderRefundLogMapper.insert(log);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void autoCancelRefund(String refundNo) {
        TyOrderRefund refund = this.getRefundByRefundNo(refundNo);
        if (refund != null && refund.getStatus() == OrderEnums.RefundDetailStatus.WAIT_BUYER_RETURN.getValue()) {
            TyOrderRefund updateRefund = new TyOrderRefund();
            updateRefund.setId(refund.getId());
            updateRefund.setStatus(OrderEnums.RefundDetailStatus.CLOSED.getValue());
            orderRefundMapper.updateByPrimaryKeySelective(updateRefund);

            TyOrder updateOrder = new TyOrder();
            updateOrder.setId(refund.getOrderId());
            updateOrder.setRefundStatus(OrderEnums.RefundStatus.REFUND_FAILED.getValue());
            orderMapper.updateByPrimaryKeySelective(updateOrder);

            //记录
            TyOrderRefundLog log = new TyOrderRefundLog();
            log.setRefundId(refund.getId());
            log.setRefundNo(refund.getRefundNo());
            log.setOperatorId(refund.getMemberId());
            log.setOperatorName(refund.getMemberName());
            log.setHeadImg(refund.getHeadImg());
            log.setContent("买家超时未寄货,退款申请自动取消");
            log.setAddTime(DateUtil.date());
            log.setUpdTime(log.getAddTime());
            orderRefundLogMapper.insert(log);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void autoConfirmRefund(String refundNo) {
        TyOrderRefund refund = this.getRefundByRefundNo(refundNo);
        if (refund != null && refund.getStatus() == OrderEnums.RefundDetailStatus.BUYER_RETURNED.getValue()) {
            TyOrderRefund updateRefund = new TyOrderRefund();
            updateRefund.setId(refund.getId());
            updateRefund.setStatus(OrderEnums.RefundDetailStatus.REFUND_SUS.getValue());
            orderRefundMapper.updateByPrimaryKeySelective(updateRefund);

            this.refundSusForUpdateOrder(refund);

            //记录
            TyOrderRefundLog log = new TyOrderRefundLog();
            log.setRefundId(refund.getId());
            log.setRefundNo(refund.getRefundNo());
            log.setOperatorId(refund.getShopId());
            log.setOperatorName(refund.getShopName());
            log.setContent("商家超时未处理,自动确认收货,退款成功");
            log.setAddTime(DateUtil.date());
            log.setUpdTime(log.getAddTime());
            orderRefundLogMapper.insert(log);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void cancelRefund(UmsMember member, Integer refundId) throws ServiceException {
        TyOrderRefund refund = this.getRefundByMember(member, refundId);
        if (!CollectionUtil.newArrayList(
                OrderEnums.RefundDetailStatus.APPLY.getValue(),
                OrderEnums.RefundDetailStatus.WAIT_BUYER_RETURN.getValue(),
                OrderEnums.RefundDetailStatus.BUYER_RETURNED.getValue(),
                OrderEnums.RefundDetailStatus.SALES_REFUSE.getValue(),
                OrderEnums.RefundDetailStatus.SERVICE_IN.getValue()
        ).contains(refund.getStatus())) {
            throw new ServiceException("order.refund.status.error");
        }
        TyOrderRefund updateRefund = new TyOrderRefund();
        updateRefund.setId(refund.getId());
        updateRefund.setStatus(OrderEnums.RefundDetailStatus.CLOSED.getValue());
        orderRefundMapper.updateByPrimaryKeySelective(updateRefund);


        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(refund.getOrderId());
        updateOrder.setRefundStatus(OrderEnums.RefundStatus.REFUND_FAILED.getValue());
        orderMapper.updateByPrimaryKeySelective(updateOrder);

        //记录
        TyOrderRefundLog log = new TyOrderRefundLog();
        log.setRefundId(refund.getId());
        log.setRefundNo(refund.getRefundNo());
        log.setOperatorId(refund.getMemberId());
        log.setOperatorName(refund.getMemberName());
        log.setHeadImg(refund.getHeadImg());
        log.setContent("买家取消退款申请");
        log.setAddTime(DateUtil.date());
        log.setUpdTime(log.getAddTime());
        orderRefundLogMapper.insert(log);
    }

    @Override
    public TyOrderRefundResult getOrderRefundByDetailId(Integer detailId) {
        System.out.println("detailId"+detailId);
        TyOrderRefundExample example = new TyOrderRefundExample();
        example.setOrderByClause("add_time desc");
        example.createCriteria().andOrderIdEqualTo(detailId);
        List<TyOrderRefund> refundList = orderRefundMapper.selectByExample(example);

        if (CollectionUtil.isEmpty(refundList)) {
            return null;
        }
        TyOrderRefundResult result = new TyOrderRefundResult();
        result.setRefund(refundList.get(0));

        TyOrderRefundLogExample logExample = new TyOrderRefundLogExample();
        logExample.setOrderByClause("add_time desc");
        logExample.createCriteria().andRefundIdEqualTo(refundList.get(0).getId());
        result.setRefundLogList(orderRefundLogMapper.selectByExample(logExample));


        TyOrderExample tyorderExample = new TyOrderExample();
//        tyorderExample.setOrderByClause("add_time desc");
//        tyorderExample.createCriteria().andRefundIdEqualTo(refundList.get(0).getId());
        result.setTyOrder(orderMapper.selectByPrimaryKey(detailId));

        return result;
    }

    @Override
    public TyOrderRefund getOrderRefundByRefundNo(String refundNo) {
        TyOrderRefundExample example = new TyOrderRefundExample();
        example.createCriteria().andRefundNoEqualTo(refundNo);
        List<TyOrderRefund> refundList = orderRefundMapper.selectByExample(example);
        return CollectionUtil.isNotEmpty(refundList) ? refundList.get(0) : null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void refundSusCallback(TyOrderRefund refund) {
        TyOrderRefund updateRefund = new TyOrderRefund();
        updateRefund.setId(refund.getId());
        updateRefund.setStatus(OrderEnums.RefundDetailStatus.REFUND_SUS.getValue());
        orderRefundMapper.updateByPrimaryKeySelective(updateRefund);

        this.refundSusForUpdateOrder(refund);
    }

    private TyOrderRefund getRefundByShop(UmsShop shop, Integer refundId) throws ServiceException {
        TyOrderRefundExample example = new TyOrderRefundExample();
        example.createCriteria().andShopIdEqualTo(shop.getId()).andIdEqualTo(refundId);
        List<TyOrderRefund> list = orderRefundMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(list)) {
            throw new ServiceException("order.refund.wait.noexist");
        }
        return list.get(0);
    }

    private TyOrderRefund getRefundByMember(UmsMember member, Integer refundId) throws ServiceException {
        TyOrderRefundExample example = new TyOrderRefundExample();
        example.createCriteria().andMemberIdEqualTo(member.getId()).andIdEqualTo(refundId);
        List<TyOrderRefund> list = orderRefundMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(list)) {
            throw new ServiceException("order.refund.wait.noexist");
        }
        return list.get(0);
    }

    private TyOrderRefund getRefundByRefundNo(String refundNo) {
        TyOrderRefundExample example = new TyOrderRefundExample();
        example.createCriteria().andRefundNoEqualTo(refundNo);
        List<TyOrderRefund> list = orderRefundMapper.selectByExample(example);
        return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
    }
}
